﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

using SmallERP.MODEL.PrintManage;
using SmallERP.DAL;
using SmallERP.DAL.PrintManage;
using SmallERP.COM;
using System.Data.Common;
using SmallERP.Bll.Com;
using System.Data;
using Smallerp.Contracts;

namespace SmallERP.Bll.PrintManage
{
    public class BoardBLL : IDataAccess
    {
        IOperateDB _OperateDb;
        public BoardBLL(IOperateDB inOp)
        {
            _OperateDb = inOp;
        }
        /// <summary>
        /// 获得大版列表
        /// </summary>
        /// <param name="status"></param>
        /// <param name="printerId"></param>
        /// <param name="measureUnit"></param>
        /// <returns></returns>
        public List<BoardModel> GetBoardInfoList(int status, int printerId, int measureUnit)
        {
            DateTime now = UnityMethod.GetSystemTime();
            DateTime dtStart = DateTime.Now.Date.AddDays(-0.5);
            DateTime dtEnd = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
            List<BoardModel> list = new List<BoardModel>();
            //using (smallerpDataContext entities = new smallerpDataContext())
            //{
            //    List<Board> boardList = null;
            //    if (status == -1)//今日全部大板
            //    {
            //        boardList = entities.Board.Where(b => b.Status != (int)Status.EnumBoardStatus.WaitEncrypt && b.PrinterId == printerId && b.LastPrintTime >= dtStart && b.LastPrintTime <= dtEnd).OrderBy(b => b.CreateTime).ThenByDescending(b => b.PrintPriority).ToList();
            //    }
            //    else if (status == 2)//今日打印
            //    {
            //        boardList = entities.Board.Where(b => b.Status == status && b.PrinterId == printerId && b.LastPrintTime >= dtStart && b.LastPrintTime <= dtEnd).OrderBy(b => b.CreateTime).ThenByDescending(b => b.PrintPriority).ToList();
            //    }
            //    else
            //    {
            //        //boardList = entities.Board.Where(b => b.Status == status && b.PrinterId == printerId).OrderBy(b => b.CreateTime).ThenByDescending(b => b.PrintPriority).ToList();
            //        boardList = entities.Board.Where(b => b.Status == status && b.PrinterId == printerId).ToList().OrderByDescending(b => b.PrintPriority).ThenBy(b=>b.CreateTime).ToList();
            //        //boardList = boardList.OrderBy(b => b.CreateTime).ToList();
            //    }

            //    foreach (var item in boardList)
            //    {
            //        if (!item.PaperFaceReference.IsLoaded)
            //        {
            //            item.PaperFaceReference.Load();
            //        }
            //        if (!item.PaperTypeReference.IsLoaded)
            //        {
            //            item.PaperTypeReference.Load();
            //        }
            //        BoardModel boardInfo = MappingBoardToModel(item, measureUnit);
            //        list.Add(boardInfo);
            //    }
            //}

            string QueryBoardinfo;
            DataTable tableBoard;
            if (status == -1)
            {
                QueryBoardinfo = " select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and printerid=" + printerId + " and CreateTime>#" + dtStart + "# and createtime <#" + dtEnd + "# order by PrintPriority desc,CreateTime";
                
            }
            else if (status == 2)
            {
                QueryBoardinfo = " select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and printerid=" + printerId + " and CreateTime>#" + dtStart + "# and createtime <#" + dtEnd + "#  and status= 1 order by PrintPriority desc,CreateTime";
            }
            else
            {
                QueryBoardinfo = " select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and printerid=" + printerId + " and status=" + status + " order by PrintPriority desc,CreateTime";
            }
            tableBoard = _OperateDb.QueryDataTable(QueryBoardinfo);
            
            return MappingBoardToModel(tableBoard,measureUnit);
        }

        public List<BoardModel> GetBoardInfoForQuery(int boardId, int photoid, string customerName, int measureUnit, int printerId)
        {
            List<BoardModel> list = new List<BoardModel>();

            //using (smallerpDataContext entities = new smallerpDataContext())
            //{
            //    smallerpDataContext db = new smallerpDataContext();
                
            //    if (boardId != 0)
            //    {
            //        BoardModel boardInfo = null;
            //        Board board = entities.Board.FirstOrDefault(b => b.BoardId == boardId && b.PrinterId == printerId);
            //        if (board != null)
            //        {
            //            if (!board.PaperFaceReference.IsLoaded)
            //            {
            //                board.PaperFaceReference.Load();
            //            }
            //            if (!board.PaperTypeReference.IsLoaded)
            //            {
            //                board.PaperTypeReference.Load();
            //            }
            //            boardInfo = MappingBoardToModel(board, measureUnit);
            //        }
            //        else
            //        {
            //            boardInfo = null;
            //        }
            //        list.Add(boardInfo);
            //    }
            //    if (photoid != 0)
            //    {
            //        list.Clear();
            //        photoInfo photo = entities.photoInfo.FirstOrDefault(p => p.PhotoId == photoid);
            //        if (photo != null)
            //        {
            //            if (!photo.PicMakeUp.IsLoaded)
            //            {
            //                photo.PicMakeUp.Load();
            //            }
            //            foreach (var item in photo.PicMakeUp)
            //            {
            //                if (!item.BoardReference.IsLoaded)
            //                {
            //                    item.BoardReference.Load();
            //                }

            //                if (!item.Board.PaperFaceReference.IsLoaded)
            //                {
            //                    item.Board.PaperFaceReference.Load();
            //                }
            //                if (!item.Board.PaperTypeReference.IsLoaded)
            //                {
            //                    item.Board.PaperTypeReference.Load();
            //                }
            //                BoardModel boardInfo = MappingBoardToModel(item.Board, measureUnit);
            //                if (boardInfo.PrinterId == printerId)
            //                {
            //                    list.Add(boardInfo);
            //                }

            //            }
            //        }
            //    }
            //    if (customerName != string.Empty)
            //    {

            //        list.Clear();
            //        List<int> boardidlist = BoardDAL.GetListBoardId(customerName);

            //        foreach (var item in boardidlist)
            //        {
            //            Board bd = entities.Board.FirstOrDefault(b => b.BoardId == item);
            //            if (!bd.PaperFaceReference.IsLoaded)
            //            {
            //                bd.PaperFaceReference.Load();
            //            }
            //            if (!bd.PaperTypeReference.IsLoaded)
            //            {
            //                bd.PaperTypeReference.Load();
            //            }
            //            BoardModel boardInfo = MappingBoardToModel(bd, measureUnit);
            //            list.Add(boardInfo);
            //        }
            //    }
            //}
            if (boardId != 0)
            {
                string QueryBoardStr = "select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate  from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and boardid=" + boardId;
                DataTable tableBoard = _OperateDb.QueryDataTable(QueryBoardStr);
                list.AddRange(MappingBoardToModel(tableBoard, measureUnit));

            }
            if (photoid != 0)
            {
                string QueryboardStr = " select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and boardid=(select boardid from picmakeup where photoid=" + photoid + ")";
                DataTable tableBoard = _OperateDb.QueryDataTable(QueryboardStr);
               list.AddRange(MappingBoardToModel(tableBoard, measureUnit));
            }
            if (customerName != string.Empty)
            {
                string QueryboardStr = "select AutoPoint,BoardId,CreateTime,DPI,Height,LastPrintTime,Length,board.PaperFaceId,PaperFaceName,board.PaperTypeId,PaperTypeName,PicPath,PrinterId,PrintNum,PrintPaperId,PrintPriority,Remark,Status,WasteRate from board,papertype,paperface where board.papertypeid=papertype.papertypeid and board.paperfaceid=paperface.paperfaceid and boardid in (select distinct d.BoardId from orderInfo a,photoINfo b,picmakeup c,board d where a.orderproductid =b.orderproductid and b.photoid =c.photoid and c.boardid =d.boardid and a.ordername like'%"+customerName+"%') ";
                DataTable tableBoard = _OperateDb.QueryDataTable(QueryboardStr);
                list.AddRange(MappingBoardToModel(tableBoard, measureUnit));

            }
            return list;
        }
        private List<BoardModel> MappingBoardToModel(DataTable tableBoard, int measureUnit)
        {
            List<BoardModel> list = new List<BoardModel>(); 
            for (int i = 0; i < tableBoard.Rows.Count; i++)
            {
                BoardModel board = new BoardModel()
                {
                    AutoPoint = Convert.ToString(tableBoard.Rows[i]["AutoPoint"]),
                    BoardId = Convert.ToInt32(tableBoard.Rows[i]["BoardId"]),
                    CreateTime = Convert.ToDateTime(tableBoard.Rows[i]["Createtime"]),
                    DPI = Convert.ToInt32(tableBoard.Rows[i]["DPI"]),
                    Height = Convert.ToInt32(tableBoard.Rows[i]["Height"]),
                    LastPrintTime = Convert.ToDateTime(tableBoard.Rows[i]["LastPrintTime"]),
                    Length = Convert.ToInt32(tableBoard.Rows[i]["Length"]),
                    PaperFaceId = Convert.ToInt32(tableBoard.Rows[i]["PaperFaceId"]),
                    PaperFaceName = Convert.ToString(tableBoard.Rows[i]["PaperFaceName"]),
                    PaperTypeId = Convert.ToInt32(tableBoard.Rows[i]["PaperTypeId"]),
                    PaperTypeName = Convert.ToString(tableBoard.Rows[i]["PaperTypeName"]),
                    PicPath = Convert.ToString(tableBoard.Rows[i]["PicPath"]),
                    PrinterId = Convert.ToInt32(tableBoard.Rows[i]["PrinterId"]),
                    PrintNum = Convert.ToInt32(tableBoard.Rows[i]["PrintNum"]),
                    PrintPaperId = Convert.ToInt32(tableBoard.Rows[i]["PrintPaperId"]),
                    PrintPriority = Convert.ToInt32(tableBoard.Rows[i]["PrintPriority"]),
                    Remark = Convert.ToString(tableBoard.Rows[i]["Remark"]),
                    Status = Convert.ToInt32(tableBoard.Rows[i]["Status"]),
                    WasteRate = Convert.ToDouble(tableBoard.Rows[i]["WasteRate"])

                };
                switch (measureUnit)
                {
                    case (int)Status.MeasureUnit.Inch:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * board.Length / board.DPI), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI, 2);
                        break;
                    case (int)Status.MeasureUnit.Cm:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI * 2.54, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI * 2.54, 2);
                        break;
                    case (int)Status.MeasureUnit.Meter:
                        board.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54 / 10000), 4);
                        board.widthView = Math.Round((double)board.Height / board.DPI * 2.54 / 100, 2);
                        board.LengthView = Math.Round((double)board.Length / board.DPI * 2.54 / 100, 2);
                        break;
                    default:
                        break;
                }

                list.Add(board);
            }
            return list;
        }
        //private BoardModel MappingBoardToModel(Board board, int measureUnit)
        //{
        //    BoardModel boardInfo = new BoardModel();
        //    if (board != null)
        //    {

        //        boardInfo.BoardId = board.BoardId;
        //        boardInfo.CreateTime = board.CreateTime;
        //        boardInfo.DPI = board.DPI;
        //        boardInfo.LastPrintTime = board.LastPrintTime;
        //        boardInfo.PaperFaceId = board.PaperFace.PaperFaceId;
        //        boardInfo.PaperFaceName = board.PaperFace.PaperFaceName;
        //        boardInfo.PaperTypeId = board.PaperType.PaperTypeId;
        //        boardInfo.PaperTypeName = board.PaperType.PaperTypeName;
        //        boardInfo.PicPath = board.picPath;
        //        boardInfo.PrinterId = board.PrinterId;
        //        boardInfo.PrintNum = board.PrintNum;
        //        boardInfo.PrintPaperId = board.PrintPaperId;
        //        boardInfo.PrintPriority = board.PrintPriority;
        //        boardInfo.Remark = board.Remark;
        //        boardInfo.Status = board.Status;
        //        boardInfo.Height = board.Height;
        //        boardInfo.Length = board.Length;


        //        switch (measureUnit)
        //        {
        //            case (int)Status.MeasureUnit.Inch:
        //                boardInfo.BoardArea = Math.Round((double)(board.Height / board.DPI * board.Length / board.DPI), 4);
        //                boardInfo.widthView = Math.Round((double)board.Height / board.DPI, 2);
        //                boardInfo.LengthView = Math.Round((double)board.Length / board.DPI, 2);
        //                break;
        //            case (int)Status.MeasureUnit.Cm:
        //                boardInfo.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54), 4);
        //                boardInfo.widthView = Math.Round((double)board.Height / board.DPI * 2.54, 2);
        //                boardInfo.LengthView = Math.Round((double)board.Length / board.DPI * 2.54, 2);
        //                break;
        //            case (int)Status.MeasureUnit.Meter:
        //                boardInfo.BoardArea = Math.Round((double)(board.Height / board.DPI * 2.54 * board.Length / board.DPI * 2.54 / 10000), 4);
        //                boardInfo.widthView = Math.Round((double)board.Height / board.DPI * 2.54 / 100, 2);
        //                boardInfo.LengthView = Math.Round((double)board.Length / board.DPI * 2.54 / 100, 2);
        //                break;
        //            default:
        //                break;
        //        }

               
        //        boardInfo.WasteRate = board.WasteRate;
        //    }
        //    else
        //    {
        //        boardInfo = null;
        //    }

        //    return boardInfo;
        //}

        //退版
        public int DeleteBoard(BoardModel boardInfo)
        {


            return _OperateDb.DeleteBoard(boardInfo.BoardId); ;
        }

        public int UpdateBoardFaceAndType(BoardModel inModel)
        {
            //using (smallerpDataContext db=new smallerpDataContext())
            //{
            //    try
            //    {

               
            //    Board bd = db.Board.FirstOrDefault(p => p.BoardId == inModel.BoardId);
            //    bd.PaperFace = db.PaperFace.FirstOrDefault(p=>p.PaperFaceId==inModel.PaperFaceId);
            //    bd.PaperType = db.PaperType.FirstOrDefault(p => p.PaperTypeId == inModel.PaperTypeId);
            //    db.SaveChanges();
            //    }
            //    catch (Exception exx)
            //    {

            //        return -1;
            //    }
            //    return 1;
            //}

            string UpdateBoard = "update board set PaperFaceId=" + inModel.PaperFaceId + ", PaperTypeId=" + inModel.PaperTypeId + " where boardid=" + inModel.BoardId;
            return _OperateDb.ExecuteNonQuery(UpdateBoard)>0?1:0;
        }

        #region IDataAccess 成员

        public int Insert(object o)
        {
            throw new NotImplementedException();
        }


        /// <summary>
        /// 重新打印
        /// </summary>
        /// <param name="board"></param>
        /// <param name="newRecordList">重新打板后生成的浪费记录</param>
        /// <returns></returns>
        public int RePrint(BoardModel boardInfo, out List<int> newRecordIDList)
        {
            int result = 0;
            newRecordIDList = new List<int>();
            //List<PaperWasteRecords>  newRecordList = new List<PaperWasteRecords>();

            //using (smallerpDataContext entities = new smallerpDataContext())
            //{
            //    Board board = entities.Board.FirstOrDefault(b => b.BoardId == boardInfo.BoardId);
            //    if (board==null)
            //    {
            //        return -1;
            //    }
            //    //将大板上的照片都记录返工浪费
            //    if (!board.PicMakeUp.IsLoaded)
            //    {
            //        board.PicMakeUp.Load();
            //    }
            //    string strPaperWrasteName = "重新打印（返片）";
            //    PaperInfo paper = entities.PaperInfo.FirstOrDefault(p => p.PrintPaperId == board.PrintPaperId);

            //    SmallERP.DAL.PaperWasteType pwt = entities.PaperWasteType.FirstOrDefault(p => p.PaperOperationTypeName == strPaperWrasteName);
            //    if (pwt == null)
            //    {
            //        pwt = new SmallERP.DAL.PaperWasteType()
            //        {
            //            PaperOperationTypeName = strPaperWrasteName
            //        };
            //        entities.AddToPaperWasteType(pwt);
            //        entities.SaveChanges();
            //    }

            //    foreach (var pm in board.PicMakeUp.ToList())
            //    {
            //        if (!pm.photoInfoReference.IsLoaded)
            //        {
            //            pm.photoInfoReference.Load();
            //        }

            //        PaperWasteRecords records = new PaperWasteRecords()
            //        {
            //            Length = (pm.photoInfo.Height * 2.54) / 100,
            //            Width = (pm.photoInfo.Width * 2.54) / 100,
            //            PaperWasteType = pwt,
            //            Remark = strPaperWrasteName,
            //            Status = (int)Status.WasterPaperStatus.unSure,
            //            CreateTime = UnityMethod.GetSystemTime(),
            //            PaperInfo = paper
            //        };
            //        newRecordList.Add(records);
            //        entities.AddToPaperWasteRecords(records);
            //    }

            //    board.PrintPaperId = 0;
            //    board.Status = boardInfo.Status;

            //    entities.SaveChanges();

            //    newRecordIDList = newRecordList.Select(r => r.Id).ToList();
            //}
            return _OperateDb.RePrint(boardInfo.BoardId,boardInfo.PrintPaperId);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public int Update(object o)
        {
            int ret = 0;
            BoardModel boardInfo = (BoardModel)o;
            //using (smallerpDataContext entities = new smallerpDataContext())
            //{
            //    try
            //    {
            //        Board board = entities.Board.FirstOrDefault(b => b.BoardId == boardInfo.BoardId);
            //        board.Status = boardInfo.Status;
            //        board.PrintNum = boardInfo.PrintNum;
            //        board.PrintPriority = boardInfo.PrintPriority;
            //        board.LastPrintTime = boardInfo.LastPrintTime;
            //        board.PrintPaperId = boardInfo.PrintPaperId;              

            //        entities.SaveChanges();
            //    }
            //    catch (Exception ex)
            //    {
            //        ret = -1;
            //    }
            //}
            string upBoard = "update board set Status=" + boardInfo.Status + ", PrintNum=" + boardInfo.PrintNum + ",PrintPriority=" + boardInfo.PrintPriority + ",LastPrintTime='" + boardInfo.LastPrintTime + "',PrintPaperId=" + boardInfo.PrintPaperId + " where BoardId=" + boardInfo.BoardId;
            int updateBoard = _OperateDb.ExecuteNonQuery(upBoard);
          
            if (updateBoard > 0)
            {

                ret = 0;
                if (boardInfo.Status == (int)(int)SmallERP.COM.Status.EnumBoardStatus.Printed)
                {
                    string updatephoto = "";
                    if (boardInfo.PrinterId == 0)
                    {
                        updatephoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.Printed + " where photoid in (select * from board,picmakeup where board.baordid=picmakeup.boardid and boardid=" + boardInfo.BoardId + ")";
                    }
                    else
                    {
                        updatephoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.Printed + ", printerid =" + boardInfo.PrinterId + " where photoid in (select photoid  from board,picmakeup where board.baordid=picmakeup.boardid and boardid=" + boardInfo.BoardId + ")";
 
                    }
                    _OperateDb.ExecuteNonQuery(updatephoto);
                }
            }
            else
            {
                ret = -1;
            }

            return ret;
        }

        public int Delete(object o)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
